﻿module Sustainalytics.News {
    import Common = Sustainalytics.Common;

    export class NewsService implements INewsService {
        private $q: ng.IQService;
        private $http: ng.IHttpService;
        private notificationFactory: Common.INotificationFactory;
        private staticObjects: Common.IStaticObjects;

        //Ctor.
        constructor($q: ng.IQService, $http: ng.IHttpService, notificationFactory: Common.INotificationFactory, staticObjects: Common.IStaticObjects) {
            this.$q = $q;
            this.$http = $http;
            this.notificationFactory = notificationFactory;
        }

        // show error message for a given error code
        private showError(err) {
            var ctx = this;
            if (err && err['code'])
                ctx.notificationFactory.error('', ctx.staticObjects.getErrorMesageByStatusCode(err, err['code']));
        }

        private showMessage(msg) {
            var ctx = this;
            ctx.notificationFactory.success(msg);
        }

        public getNewsList(skip: number, take: number, orderBy: string[], orderAscending: boolean, truncateBody: boolean, accountId: string) {
            var ctx = this;
            var def = this.$q.defer();

            var options = new Common.ListOptions();
            options.skip = skip;
            options.take = take;
            options.orderBy = orderBy;
            options.orderAscending = orderAscending;
            options.includeAllFields = true;

            var query =
                {
                    term: null,
                    category: null,
                    isPublished: true,
                    accountId: accountId,
                    truncateBody: truncateBody,
                    listOptions: options
                };

            var url = '/newsserv/api/v1/news?' + $.param(query);
            var promise = this.$http.get(url);
            promise
                .success(function (data) {
                    def.resolve(data);
                })
                .error(function (err) {
                    ctx.showError(err);
                    def.reject();
                })

            return def.promise;
        }

        public getNewsById(newsId: string, accountId: string): ng.IPromise<NewsDto> {
            var ctx = this;
            var def = this.$q.defer();
            var query =
                {
                    accountId: accountId
                };
            var url = '/newsserv/api/v1/news/' + newsId + '?' + $.param(query);
            var promise = this.$http.get(url);
            promise.success(function (data) { def.resolve(data); }).error(function (err) { ctx.showError(err); def.reject(); })
            return def.promise;
        }
    }


    // register service with News Angular module
    angular.module('Sustainalytics.News').service('NewsService',
        ['$q', '$http', 'notificationFactory', 'staticObjects', NewsService]);
}